const { VUE_PERO } = require("../config/repo");
const { promisify } = require("util");
const { program } = require("commander");
const download = promisify(require("download-git-repo"));
const { execCommand } = require("../utils/exec-command");
const { compileEjs } = require("../utils/compile-ejs");
const writeFile = require("../utils/write-file");

async function createProjectAction(project) {
  try {
    // 1. clone项目
    await download(VUE_PERO, project, { clone: true });
    // 2. 提示
    console.log(`cd ${project}`);
    console.log("npm install");
    console.log("npm run dev");

    // 3. 帮助执行npm install
    // window普平台不叫npm而是npm.cmd
    // 3.帮助执行npm install
    console.log(process.platform);
    // const commandName = process.platform === "win32" ? "npm.cmd" : "npm";
    // await execCommand(commandName, ["install"], { cwd: `./${project}` });

    // // 4.帮助执行npm run dev
    // await execCommand(commandName, ["run", "dev"], { cwd: `./${project}` });
    // 4. 帮助执行npm run dev
  } catch (error) {
    console.log("github 链接失败，请稍后重试", error);
  }
}

async function addComponentAction(cpnname) {
  // 1.创建一个组件: 编写组件的模板, 根据内容给模板中填充数据
  const result = await compileEjs("component.vue.ejs", {
    name: cpnname,
    lowername: cpnname.toLowerCase(),
  });

  // 2.将result写到到对应的文件夹中
  const dest = program.opts().dest || "src/components";
  await writeFile(`${dest}/${cpnname}.vue`, result);
  console.log("创建组件成功" + cpnname + ".vue");
}

module.exports = {
  createProjectAction,
  addComponentAction,
};
